<template>
    <el-scrollbar height="100%" style="overflow-y: hidden;"
        v-if="flag"><!-- 使用el-scrollbar组件，设置高度为100%，并隐藏垂直滚动条，只在flag为真时显示 -->
        <el-row type="flex" justify="center"
            style="align-content: center;height: 100%;margin-top: 2%"><!-- 使用flex布局的行容器，内容居中，高度100%，顶部有2%的外边距 -->
            <el-form ref="ruleFormRef" style="width: 80%;" :model="ruleForm" :rules="rules" label-width="auto"
                :size="formSize" status-icon
                :label-position="labelPosition"><!-- 表单容器，宽度80%，使用model绑定数据，rules绑定验证规则，设置表单大小、状态图标和标签位置 -->
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="上传外卖图片">
                            <el-upload :auto-upload="false" list-type="picture-card" ref="uploadRef"
                                :action="`/api/takeout/takeout-upload?id=${takeout?.id}`"
                                :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                                :before-upload="beforeAvatarUpload" :limit="1" :on-success="handleAvatarSuccess">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </el-upload> <!-- 图片上传表单项，包含上传按钮和预览对话框 -->

                            <el-dialog v-model="dialogVisible">
                                <img w-full :src="dialogImageUrl" alt="Preview Image" />
                            </el-dialog>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="外卖名称" prop="takeout_name">
                            <el-input minlength="10" maxlength="100" v-model="ruleForm.takeout_name" style="width: 100%"
                                :rows="10" type="text" />
                        </el-form-item>
                        <el-form-item label="售价" prop="price">
                            <el-input v-model="ruleForm.price" style="width: 100%" :rows="10" type="number" />
                        </el-form-item>
                        <el-form-item label="外卖类型" prop="kind">
                            <el-select v-model="ruleForm.kind" placeholder="外卖类型" size="large" style="width: 240px">
                                <el-option v-for="item in kinds" :key="item.id" :label="item.type" :value="item.id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="外卖简介" prop="introduce">
                            <el-input v-model="ruleForm.introduce" style="width: 100%" :rows="5" type="textarea"
                                minlength="15" />
                        </el-form-item>
                        <el-form-item>
                            <el-row style="width: 100%; align-content: center;margin-top: 5%;" justify="center">
                                <el-col :span="14">
                                    <el-button
                                        style="background-color: #fbaf5a; color: white; width: 100%;height: 40px;"
                                        @click="submitForm">提交外卖申请</el-button>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-row>
    </el-scrollbar>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'//导入响应式API
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'//导入UI组件和类型
import { Plus } from '@element-plus/icons-vue'//导致element图标库
import type { UploadFile, UploadProps } from 'element-plus'//导入element上传的组件类型
import type { FormProps } from 'element-plus'
import { userInfoStore } from '../assets/userStore/userStore'// 导入Element Plus上传实例的类型
import type { UploadInstance } from 'element-plus'
import { KindModel } from '../assets/models/Kind'
import router from '../router'
import { TakeoutModel } from '../assets/models/Takeout'
import { kindApis } from '../assets/apis/KindApis'// 导入API服务
import { StoreModel } from '../assets/models/Store'
import { storeApis } from '../assets/apis/StoreApis'
import { takeoutApis } from '../assets/apis/TakeoutApis'

const userStore = userInfoStore();//创建用户存储信息
const dialogImageUrl = ref<string>();//声明图片预览的URL引用
const dialogVisible = ref<boolean>(false);
const uploadRef = ref<UploadInstance>();
const kinds = ref<Array<KindModel>>([]);// 声明控制滚动条容器显示的标志引用
const flag = ref<boolean>(true) // 控制滚动条容器显示
const labelPosition = ref<FormProps['labelPosition']>('top');
const formSize = ref<ComponentSize>('large');//表单尺寸
const ruleFormRef = ref<FormInstance>();//标签位置
const takeout = ref<TakeoutModel>();
const ruleForm = reactive<TakeoutModel>({// 声明响应式表单数据
    takeout_name: '',
    introduce: '',
    store: '',
    kind: 0,
    price: 0
});


onMounted(() => {
    kindApis.queryKind()
        .then((value: Array<KindModel>) => {
            kinds.value = value;
        })
});

//文件移除事件
const handleRemove: UploadProps['onRemove'] = (file: UploadFile) => {
    console.log(file);
    router.replace('/mytakeouts');
};

//图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true;
};

//上传校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不得超过2MB!');
        return false;
    }
    return true;
}


//表单验证规则
const rules = reactive<FormRules<TakeoutModel>>({
    takeout_name: [
        {
            required: true,
            message: '请输入外卖名称',
            trigger: 'blur'
        }
    ],
    introduce: [
        {
            required: true,
            message: '请输入外卖介绍',
            trigger: 'change',
        },
    ],
    price: [
        {
            required: true,
            message: '请输入价格',
            trigger: 'change'
        }
    ],
    kind: [
        {
            required: true,
            message: '请选择类别',
            trigger: 'change'
        }
    ]
})

//提交表单处理函数
const submitForm = () => {
    storeApis.queryStore(userStore.id)
        .then((reslut: StoreModel) => {
            ruleForm.store = reslut.id!;
            takeoutApis.applyTakeout(ruleForm)
                .then((value: TakeoutModel) => {
                    if (value) {
                        ElMessage.success('外卖申请提交成功，请耐心等待审核')
                        takeout.value = value;
                        uploadRef.value?.submit();
                    } else {
                        ElMessage.error('外卖申请提交失败')
                    }
                })
        })
}

//上传成功事件
const handleAvatarSuccess: UploadProps['onSuccess'] = () => {
    router.back();
}
</script>


<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}


.header_register {
    width: 100%;
    height: 90px;
    background-color: #fbaf5a;
    padding: 20px;
}
</style>